import {Platform, SafeAreaView, ScrollView, StyleSheet, Text, TouchableOpacity, View} from "react-native";
import {SealFormData, useCreateSealForm} from "./hooks/useCreateSealForm.ts";
import React, {useState} from "react";
import {FormProvider, useFieldArray} from "react-hook-form";
import {ScreenHeader} from "./components/ScreenHeader.tsx";
import {LeaderSelector} from "../../components/LeaderSelector.tsx";
import * as FormItems from "../../components/FormItems.tsx";
import {FileImport} from "../../components/FileImport.tsx";

/**
 * @组件名称 CreateSealScreen
 *
 * @功能描述
 * 该组件负责渲染整个申请公章的表单界面。
 * 所有业务逻辑、状态管理和数据获取
 * 都已封装在 `useCreateSealForm` 钩子中。
 */

const MATERIAL_TYPE_OPTIONS = [
    {label: '非合同类', value: "1"},
    {label: '合同类材料，未经法务办审核', value: "2"},
    {label: '合同类材料，经法务办审核', value: "3"},
];

export function CreateSealScreen(props: any) {
    const {type, info} = props.route.params;
    const title = type === 'create' ? '创建新申请' : '编辑旧申请';
    // --- 逻辑与状态钩子 ---
    const {form, states, handlers} = useCreateSealForm(type, info);
    const {control, handleSubmit, watch, setValue} = form;
    const {units, sealOptions, userInfo, isSubmitting} = states;
    console.log(sealOptions)

    // --- UI 状态 ---
    // 这些是纯粹的、与表单业务逻辑无关的UI状态，保留在组件内部。
    const [uploadedFiles, setUploadedFiles] = useState<{ url: string, name: string, size: number }[]>([]);
    const [showSelector, setShowSelector] = useState<boolean>(false);

    // --- 动态字段 ---
    const sealArray = useFieldArray({
        control,
        name: 'sealTypes',
    });

    // --- 派生状态 ---
    const selectedUnit = watch('unit');
    const unitHead = watch("startUserSelectAssignees.unitHead");

    // --- 提交处理 ---
    // 组件层负责处理导航等副作用
    const handleFormSubmit = async (data: SealFormData) => {
        // 将表单数据和上传的文件对象数组一起交给钩子处理
        const success = await handlers.onSubmit(data, uploadedFiles);
        if (success) {
            props.navigation.goBack();
        }
    };

    // --- 渲染部分 ---
    return (
        <FormProvider {...form}>
            <SafeAreaView style={{
                flex: 1,
            }}>
                <ScreenHeader
                    title={title}
                    navigation={props.navigation}
                />
                <ScrollView contentContainerStyle={styles.container}>
                    <Text style={styles.h1}>{selectedUnit ? `${selectedUnit} 印章申请单` : '印章申请单'}</Text>

                    <FormItems.Pick
                        name={"unit"}
                        label="印章归属单位"
                        placeholder="请选择单位"
                        rules={{required: '请选择印章归属单位'}}
                        units={units}
                        readonly={type === 'update'} // 在修改时设为只读
                    />

                    {/* 材料名称 */}
                    <FormItems.Input
                        name={"materialName"}
                        label={"材料名称"}
                        placeholder={"关于..."}
                        rules={{require: "请输入材料名称"}}
                    />

                    {/* 材料类型 */}
                    <FormItems.Chooser
                        name={"materialType"}
                        label="材料类型"
                        rules={{required: '请选择材料类型'}}
                        options={MATERIAL_TYPE_OPTIONS}
                    />

                    {/* 印章列表 */}
                    <Text style={styles.label}>印章信息</Text>
                    {sealArray.fields.map((item, index) => (
                        <View key={item.id} style={styles.card}>
                            <FormItems.Pick
                                name={`sealTypes.${index}`}
                                label={"印章类型"}
                                placeholder={"请选择类型"}
                                units={sealOptions}
                                rules={{require: "请选择印章类型"}}
                            />

                            <FormItems.Input
                                name={`sealTypes.${index}.quantity`}
                                keyboardType={"numeric"}
                                label={"印章个数"}
                                rules={{require: "请填写印章个数"}}
                            />

                            <TouchableOpacity
                                style={styles.deleteBtn}
                                onPress={() => sealArray.remove(index)}
                            >
                                <Text style={styles.deleteTxt}>删除</Text>
                            </TouchableOpacity>
                        </View>
                    ))}

                    <TouchableOpacity
                        style={styles.appendBtn}
                        onPress={() => sealArray.append({
                            id: sealOptions[0]?.id ?? 0,
                            name: sealOptions[0]?.sealName ?? '',
                            quantity: 1,
                        })}
                    >
                        <Text style={styles.appendTxt}>添加印章</Text>
                    </TouchableOpacity>

                    <FormItems.Input
                        name={"startUserSelectAssignees.handler.name"}
                        label={"经办人"}
                        rules={{required: '请输入经办人'}}
                    />

                    <FormItems.Input
                        name={"startUserSelectAssignees.reviewer.name"}
                        label={"审核人"}
                        rules={{required: '请输入审核人'}}
                    />

                    {/* 电话 */}
                    <FormItems.Input
                        name={"phone"}
                        label={"电话"}
                        rules={{
                            required: '请输入电话号码',
                            pattern: {
                                value: /^\+?\d[\d\s\-()]{5,15}\d$/,
                                message: '不符合电话号码格式',
                            },
                        }}
                        keyboardType={"phone-pad"}
                    />

                    <FileImport
                        maxSize={1024 * 1024 * 20}
                        maxCount={10}
                        onFileChange={(files: any[]) => {
                            setUploadedFiles([...uploadedFiles, ...files]);
                        }}
                    />

                    <FormItems.MultilineInput
                        name={"attention"}
                        label={"备注"}
                    />

                    <Text style={styles.label}>单位负责人签字</Text>

                    {type === "create" &&
                        (<View>
                            <TouchableOpacity
                                style={styles.appendBtn}
                                onPress={() => {
                                    setShowSelector(true)
                                }}
                            >
                                <Text style={styles.appendTxt}>{unitHead.name || "添加负责人"}</Text>
                            </TouchableOpacity>
                            {/* 审批人选择器 */}
                            <LeaderSelector
                                visible={showSelector}
                                onClose={() => {
                                    setShowSelector(false)
                                }}
                                onConfirm={(selectedUsers) => {
                                    setValue("startUserSelectAssignees.unitHead.id", [selectedUsers[0].id])
                                    setValue("startUserSelectAssignees.unitHead.name", selectedUsers[0].nickname)
                                    setShowSelector(false)
                                }}
                                multiple={false}
                                title={'添加负责人'}
                                selectedUserIds={[]}
                                showDeptFilter={true}
                                deptId={userInfo?.deptIds}
                                currentUserId={userInfo?.id}
                            />
                        </View>)
                    }
                    {type === "update" &&
                        <View
                            style={styles.appendBtn}
                        >
                            <Text style={styles.appendTxt}>{info.signers.split("，")[2]}</Text>
                        </View>
                    }

                    <View>
                        <Text style={styles.label}>注意事项</Text>
                        <Text style={styles.notice}>
                            1.印章使用需经学院办公室主任或院长授权批准，重要文件需院长亲自审批，严禁私自使用或外借印章。{"\n"}
                            2.印章仅限用于学院正式公文、学术证明、对外合作协议、学生证明等官方文件，不得用于个人事务或商业活动。{"\n"}
                            3.印章须存放在专用保险柜中，使用后立即归还并登记，保管人员离岗时必须做好交接手续，确保印章安全。{"\n"}
                            4.每次使用印章必须详细记录使用时间、文件名称、使用人员、批准人员等信息，建立完整的使用台账备查。
                        </Text>
                    </View>
                    <TouchableOpacity
                        style={[styles.submitBtn, isSubmitting && styles.disabled]}
                        onPress={handleSubmit(handleFormSubmit)}
                        disabled={isSubmitting}
                    >
                        <Text style={styles.submitTxt}>{isSubmitting ? '提交中...' : '提交'}</Text>
                    </TouchableOpacity>
                </ScrollView>
            </SafeAreaView>
        </FormProvider>
    );
}

const styles = StyleSheet.create({
    container: {
        padding: 16,
        paddingBottom: 48,
        margin: 16,
        borderRadius: 8,
        backgroundColor: '#fff',
        shadowColor: '#000',
        shadowOffset: {
            width: 0,
            height: 2,
        },
        shadowOpacity: 0.25,
        shadowRadius: 3.84,
        elevation: 5,
    },
    center: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center',
    },
    h1: {
        fontSize: 24,
        fontWeight: 'bold',
        marginBottom: 16,
        textAlign: 'center',
    },
    label: {
        fontWeight: '600',
        marginTop: 12,
        marginBottom: 4,
    },
    input: {
        borderWidth: StyleSheet.hairlineWidth,
        borderColor: '#888',
        borderRadius: 8,
        paddingHorizontal: 8,
        paddingVertical: Platform.OS === 'ios' ? 8 : 4,
        fontSize: 16,
        height: 55
    },
    radioGroup: {
        marginVertical: 4,
    },
    radioRow: {
        flexDirection: 'row',
        alignItems: 'center',
        marginVertical: 4,
    },
    radio: {
        height: 20,
        width: 20,
        borderRadius: 10,
        borderWidth: 1,
        marginRight: 8,
        borderColor: '#666',
    },
    radioChecked: {
        backgroundColor: '#007AFF',
    },
    card: {
        borderWidth: StyleSheet.hairlineWidth,
        borderColor: '#ccc',
        borderRadius: 8,
        padding: 12,
        marginVertical: 8,
    },
    cardTitle: {
        fontWeight: 'bold',
        marginBottom: 8,
    },
    pickerWrapper: {
        borderWidth: StyleSheet.hairlineWidth,
        borderColor: '#888',
        borderRadius: 9,
        marginBottom: 8,
        height: 60,
    },
    picker: {
        height: 54,
    },
    deleteBtn: {
        alignSelf: 'flex-end',
        marginTop: 4,
    },
    deleteTxt: {
        color: 'red',
    },
    appendBtn: {
        alignSelf: 'center',
        borderWidth: StyleSheet.hairlineWidth,
        borderColor: '#007AFF',
        borderRadius: 4,
        paddingVertical: 8,
        paddingHorizontal: 16,
        marginVertical: 12,
    },
    appendTxt: {
        color: '#007AFF',
    },
    submitBtn: {
        marginTop: 24,
        backgroundColor: '#007AFF',
        borderRadius: 4,
        paddingVertical: 12,
        alignItems: 'center',
    },
    submitTxt: {
        color: '#fff',
        fontSize: 16,
    },
    disabled: {
        backgroundColor: '#aaa',
    },
    error: {
        color: 'red',
        fontSize: 12,
        marginTop: 2,
    },
    success: {
        fontSize: 18,
        color: 'green',
    },
    notice: {
        fontSize: 18,
        color: '#000',
        marginTop: 12,
    },
});